package com.hc.android.research;

import com.hc.android.research.background.BackgroundService;
import com.hc.android.research.persistence.ResearchDAO;
import com.hc.android.research.views.AddData;
import com.hc.android.research.views.DataView;
import com.hc.android.research.views.SettingsView;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AndroidResearchActivity extends Activity implements OnClickListener {
    /** 
     * Called when the activity is first created. 
     **/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button addDataBtn = (Button)findViewById(R.id.addDataViewBtn);
        addDataBtn.setOnClickListener(this);
        Button viewDataBtn = (Button)findViewById(R.id.dataViewBtn);
        viewDataBtn.setOnClickListener(this);
        Button settingsBtn = (Button)findViewById(R.id.settingsBtn);
        settingsBtn.setOnClickListener(this);
        
       updatePendingBackgroundService(this); 
    }
    
    public static void updatePendingBackgroundService(Context caller)
    {
		ResearchDAO researchDAO = new ResearchDAO();
		String delayTimeStr = researchDAO.getSetting(caller, SettingsView.SETTING_DELAY_NAME);
		long delayMillis = 10000;
		try 
		{
			delayMillis = Long.parseLong(delayTimeStr);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}

		// Start the repeating service.
		Intent intent = new Intent(caller, BackgroundService.class);
		PendingIntent pi = PendingIntent.getService(caller, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager manager = (AlarmManager) caller.getSystemService(ALARM_SERVICE);
		manager.cancel(pi);
		manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, delayMillis, pi);
	}
    
    @Override
    protected void onPause() 
    {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    
	public void onClick(View view) 
	{
		if(view.getId() == R.id.addDataViewBtn)
		{
			Intent intent = new Intent(this, AddData.class);
	    	startActivity(intent);
		} 
		else if(view.getId() == R.id.dataViewBtn)
		{
			Intent intent = new Intent(this, DataView.class);
	    	startActivity(intent);
		}
		else if(view.getId() == R.id.settingsBtn)
		{
			Intent intent = new Intent(this, SettingsView.class);
			startActivity(intent);
		}
	}
}